package org.tech4j.edi.alarm.feishu;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tech4j.common.utils.JsonUtils;
import org.tech4j.edi.alarm.api.RetryAlarmService;
import org.tech4j.edi.alarm.api.entity.PushModel;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.concurrent.CompletableFuture;

/**
 * @program: tech4j
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/10 15:08
 **/
public class FeishuRetryAlarmService implements RetryAlarmService {
    private static final Logger log = LoggerFactory.getLogger(FeishuRetryAlarmService.class);

    @Override
    public void alarmRetry(PushModel pushModel) {
        HttpClient httpClient = HttpClient.newBuilder()
                .build();
        long timestamp = System.currentTimeMillis() / 1000;
        try {
            FeishuTextContent feishuTextContent = new FeishuTextContent(pushModel.getContent());
            FeishuTextMsg msg = new FeishuTextMsg(timestamp, getSign(timestamp, pushModel.getSecret()), "text", feishuTextContent);
            HttpRequest httpRequest = HttpRequest.newBuilder()
                    .uri(new URI(pushModel.getWebhook()))
                    .POST(
                            HttpRequest.BodyPublishers
                                    .ofString(JsonUtils.toJsonString(msg))
                    ).build();
            CompletableFuture<HttpResponse<String>> future = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());
            future.whenComplete((response, throwable) -> {
                if (throwable != null) {
                    log.error("发送告警异常: ", throwable);
                } else {
                    log.info("发送告警结果: {}", response.body());
                }
            });
        } catch (Exception e) {
            // 告警异常忽略
        }
    }

    private String getSign(long timestamp, String secret) throws NoSuchAlgorithmException, InvalidKeyException, URISyntaxException, IOException, InterruptedException {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64.getEncoder().encode(signData));
    }

    private static class FeishuTextMsg {
        private long timestamp;
        private String sign;
        private String msg_type;
        private FeishuTextContent content;

        public FeishuTextMsg(long timestamp, String sign, String msg_type, FeishuTextContent content) {
            this.timestamp = timestamp;
            this.sign = sign;
            this.msg_type = msg_type;
            this.content = content;
        }

        public long getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(long timestamp) {
            this.timestamp = timestamp;
        }

        public String getSign() {
            return sign;
        }

        public void setSign(String sign) {
            this.sign = sign;
        }

        public String getMsg_type() {
            return msg_type;
        }

        public void setMsg_type(String msg_type) {
            this.msg_type = msg_type;
        }

        public FeishuTextContent getContent() {
            return content;
        }

        public void setContent(FeishuTextContent content) {
            this.content = content;
        }
    }

    private static class FeishuTextContent {
        private String text;

        public FeishuTextContent(String text) {
            this.text = text;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    }
}
